package com.david.config;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import com.david.baidu.ueditor.ActionEnter;

/**
 * 用于处理关于ueditor插件相关的请求
 *
 */
public class UeditorController extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setHeader("Content-Type", "text/html");
        PrintWriter out = response.getWriter();
        ServletContext application = this.getServletContext();
        String rootPath = application.getRealPath("/");
        String action = request.getParameter("action");
        String result = new ActionEnter(request, rootPath).exec();
        if (action != null && (action.equals("listfile") || action.equals("listimage"))) {
            rootPath = rootPath.replace("\\", "/");
            result = result.replaceAll(rootPath, "/");
        }
        out.write(result);
    }

    @Override
    public void init() throws ServletException {
        super.init();
    }

    @RequestMapping(value = "/exec")
    @ResponseBody
    public void exec(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setHeader("Content-Type", "text/html");
        String rootPath = request.getServletContext().getRealPath("/static/upload");
        response.getWriter().write(new ActionEnter(request, rootPath).exec());
    }
}